/**
 * 
 */
package at.ac.lbg.media.vis.framework.persistence;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import at.ac.lbg.media.vis.framework.domain.CategoryDO;

/**
 * @author Evelyn Münster
 *
 */
public class CategoryDAO implements ICategoryDAO {
	
	private HibernateTemplate hibernateTemplate;
	protected final Log logger = LogFactory.getLog(getClass());
	List<CategoryDO> allCategories = null;
	List<CategoryDO> keywords = null;
	List<CategoryDO> categories = null;
	List<CategoryDO> sections = null;
	
	public CategoryDAO() {}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<CategoryDO> getKeywords() {
		if (keywords != null) {
			return keywords;
		}
		String queryString = "from CategoryDO as cat where cat.level = 3 order by countartworks DESC";
		try {
		    keywords = (List<CategoryDO>) hibernateTemplate.find(queryString);
		} catch (DataAccessException e) {
			logger.error("Could not load leafcategories: " + queryString, e);
		}
		return keywords;
	}
	
	
	

	@Override
	@SuppressWarnings("unchecked")
	public List<CategoryDO> getCategories() {
		String queryString = "from CategoryDO as cat where cat.level = 2 order by sorting";
		try {
		    categories = (List<CategoryDO>) hibernateTemplate.find(queryString);
		} catch (DataAccessException e) {
			logger.error("Could not load mainCategories: " + queryString, e);
		}
		return categories;
	}
	
	@Override
    @SuppressWarnings("unchecked")
    public List<CategoryDO> getCategories(int sectionId) {
	    Long sId = new Integer(sectionId).longValue();
        String queryString = "from CategoryDO as cat where cat.level = 2 and cat.parentCategory.id = ? order by sorting";
        try {
            categories = (List<CategoryDO>) hibernateTemplate.find(queryString, sId);
        } catch (DataAccessException e) {
            logger.error("Could not load mainCategories: " + queryString, e);
        }
        return categories;
    }
	
	@Override
	@SuppressWarnings("unchecked")
    public List<CategoryDO> getSections() {
        if (sections != null) {
            return sections;
        }
        String queryString = "from CategoryDO as cat where cat.level = 1 order by sorting";
        try {
            sections = (List<CategoryDO>) hibernateTemplate.find(queryString);
        } catch (DataAccessException e) {
            logger.error("Could not load mainCategories: " + queryString, e);
        }
        return sections;
    }


	/**
	 * @param hibernateTemplate the hibernateTemplate to set
	 */
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	

}
